<template>
	<div class="sku-select">
		<div class="sku-type">
			<el-radio v-model="radio" label="1">单规格</el-radio>
			<el-radio v-model="radio" label="2">多规格</el-radio>
		</div>
		<div class="sku-single" v-if="radio === '1'">
			<el-form
				ref="form"
				:model="item"
				label-width="120px"
				v-for="(item, index) in form"
				:key="index"
				:inline="true"
			>
				<!--					                <el-form-item label="图片">-->
				<!--					                    <file-list :value="item.pic" :limit="1"></file-list>-->
				<!--					                </el-form-item>-->
				<el-form-item label="规格">
					<el-input
						v-model="item.specification"
						size="mini"
						placeholder="请输入规格"
						@change="onChange"
						clearable
					></el-input>
				</el-form-item>
				<el-form-item label="售价(拼团价)">
					<el-input
						v-model="item.endprice"
						size="mini"
						placeholder="请输入售价"
						@change="onChange"
						clearable
					></el-input>
				</el-form-item>
				<el-form-item label="成本价">
					<el-input
						v-model="item.costprice"
						size="mini"
						placeholder="请输入成本价"
						@change="onChange"
						clearable
					></el-input>
				</el-form-item>
				<el-form-item label="原价">
					<el-input
						v-model="item.price"
						size="mini"
						placeholder="请输入原价"
						@change="onChange"
						clearable
					></el-input>
				</el-form-item>
				<el-form-item label="库存">
					<el-input
						v-model="item.surplus"
						size="mini"
						placeholder="请输入库存"
						@change="onChange"
						clearable
					></el-input>
				</el-form-item>
			</el-form>
		</div>
		<div class="sku-multi" v-if="radio === '2'">
			<div class="sku-tool">
				<span>选择规格：</span>
				<el-select
					v-model="selects.skuId"
					placeholder="请选择规格模板"
					@change="onSkuSelect"
				>
					<el-option
						v-for="item in skuList"
						:key="item.id"
						:label="item.name"
						:value="item.id"
					>
					</el-option>
				</el-select>
				<!--				<el-button-->
				<!--					type="primary"-->
				<!--					size="mini"-->
				<!--					style="margin-left: 10px;"-->
				<!--					@click="onSkuSelect()"-->
				<!--					>确认</el-button-->
				<!--				>-->
				<el-button
					type="default"
					size="mini"
					style="margin-left: 10px;"
					@click="onSkuTemplateAdd()"
					>添加规则</el-button
				>
			</div>
			<div class="sku-nodes">
				<div class="nodes-item" v-for="(item, index) in nodes" :key="index">
					<div class="sku-name">
						<span style="margin-left: 14px;color:#FF4400;">规格名：</span>
						<el-input
							v-model="item.name"
							size="mini"
							style="width: 120px;margin-top: 10px;"
							placeholder="请输入规格名"
							:key="'nodesName' + index"
							@input="onValueInput"
							clearable
						></el-input>
						<el-button type="text" style="margin-left: 10px" @click="onSkuDelete(index)"
							>删除</el-button
						>
					</div>
					<!--					<el-tag-->
					<!--						:key="tag.name"-->
					<!--						type="danger"-->
					<!--						v-for="(tag, tagIndex) in item.descResult"-->
					<!--						:disable-transitions="false"-->
					<!--						closable-->
					<!--						style="margin-right: 10px;"-->
					<!--						@close="onValueDelete(index, tagIndex)"-->
					<!--					>-->
					<!--						{{ tag.name }}-->
					<!--					</el-tag>-->
					<span style="margin-left: 14px">规格值：</span>
					<template v-for="(skuValue, skuIndex) in nodes[index].descResult">
						<el-input
							style="width: 120px;margin-right: 10px;margin-top: 10px;"
							placeholder="请输入规格值"
							v-model="nodes[index].descResult[skuIndex].name"
							size="mini"
							:key="'nodesDesc' + skuIndex"
							@input="onValueInput"
							clearable
						></el-input>
						<el-button
							type="text"
							size="mini"
							@click="onValueDelete(index, skuIndex)"
							v-if="nodes[index].descResult.length > 1"
							style="margin-right: 10px"
							:key="'descResult' + skuIndex"
							>删除</el-button
						>
					</template>
					<el-button type="text" size="mini" @click="onValueAdd(index)">添加</el-button>
					<!--                    <el-button v-else class="button-new-tag" size="small" @click="showInput(index)">+ 添加规格</el-button>-->
				</div>
				<el-button
					type="default"
					size="mini"
					@click="onSkuAdd()"
					v-if="nodes.length > 0"
					style="margin-top: 10px;"
					>添加新规格</el-button
				>
			</div>
			<div class="bitch-operate" style="margin-bottom: 10px">
				<el-button
					type="primary"
					size="mini"
					@click="onSkuCreate()"
					style="margin-bottom: 14px"
					>立即生成</el-button
				>
				<template v-if="resultNodes.length > 0">
					<span style="margin-left: 50px">批量操作：</span>
					<el-input
						v-model="endprice"
						size="mini"
						placeholder="请输入售价"
						clearable
						style="width: 110px"
						@input="onBitchEndprice"
					></el-input>
					<el-input
						v-model="costprice"
						size="mini"
						placeholder="请输入成本价"
						clearable
						style="width: 110px;margin-left: 22px;"
						@input="onBitchCostprice"
					></el-input>
					<el-input
						v-model="price"
						size="mini"
						placeholder="请输入原价"
						clearable
						style="width: 110px;margin-left: 22px;"
						@input="onBitchPrice"
					></el-input>
					<el-input
						v-model="surplus"
						size="mini"
						placeholder="请输入库存"
						clearable
						style="width: 110px;margin-left: 22px;"
						@input="onBitchSurplus"
					></el-input>
				</template>
			</div>
			<el-form
				ref="form"
				:model="item"
				label-width="120px"
				v-for="(item, index) in resultNodes"
				:inline="true"
				:key="'resultNodes' + index"
			>
				<el-form-item label="规格">
					<div class="specification" :title="item.specification" style="cursor: pointer">
						{{ item.specification }}
					</div>
				</el-form-item>
				<el-form-item label="售价(拼团价)">
					<el-input
						v-model="item.endprice"
						size="mini"
						placeholder="请输入售价"
						clearable
						@input="onValueEmit"
					></el-input>
				</el-form-item>
				<el-form-item label="成本价">
					<el-input
						v-model="item.costprice"
						size="mini"
						placeholder="请输入成本价"
						clearable
						@input="onValueEmit"
					></el-input>
				</el-form-item>
				<el-form-item label="原价">
					<el-input
						v-model="item.price"
						size="mini"
						placeholder="请输入原价"
						clearable
						@input="onValueEmit"
					></el-input>
				</el-form-item>
				<el-form-item label="库存">
					<el-input
						v-model="item.surplus"
						size="mini"
						placeholder="请输入库存"
						clearable
						@input="onValueEmit"
					></el-input>
				</el-form-item>
			</el-form>
		</div>

		<cl-form ref="cl-form"></cl-form>
	</div>
</template>

<script>
import SkuCreate from './SkuCreate';
// import fileList from '@/components/feilList';
export default {
	name: 'SkuSelect',
	components: {
		// fileList
	},
	props: {
		value: {
			type: String,
			default: () => {
				return '';
			}
		}
	},
	data() {
		return {
			radio: '1',
			form: [
				{
					specification: '默认',
					endprice: '',
					costprice: '',
					price: '',
					surplus: ''
				}
			],
			skuList: [],
			selects: {
				skuId: ''
			},
			nodes: [],
			resultNodes: [],
			isFirst: false
		};
	},
	created() {
		this.$service.goods.specification.list().then(res => {
			this.skuList = res;
		});
	},
	methods: {
		onSkuTemplateAdd() {
			let that = this;
			this.$refs['cl-form'].open({
				props: {
					title: '添加规格模板',
					width: '950px',
					labelWidth: '120px'
				},
				items: [
					{
						prop: 'name',
						label: '模板名称：',
						component: {
							name: 'el-input',
							attrs: {
								placeholder: '请输入属性规格名',
								clearable: true
							}
						},
						rules: [
							{
								required: true,
								message: '属性规格名不能为空'
							}
						]
					},
					{
						prop: 'nodes',
						label: '规格内容：',
						component: SkuCreate,
						rules: [
							{
								validator: (rule, value, callback) => {
									if (!value) {
										callback(new Error('规格不能为空'));
									} else {
										let arr = JSON.parse(value);
										let flag = true;
										arr.forEach(item => {
											if (!item.name) {
												flag = false;
												callback(new Error('规格名不能为空'));
											}
											item.desc.forEach(desc => {
												if (!desc.name) {
													flag = false;
													callback(new Error('规格值不能为空'));
												}
											});
										});
										if (flag) {
											callback();
										}
									}
								},
								required: true
							}
						]
					}
				],

				on: {
					submit: ({ data, done, close }) => {
						that.$service.goods.specification
							.add({
								parentId: 0,
								name: data.name
							})
							.then(res => {
								let nodes = JSON.parse(data.nodes);
								nodes.forEach(async nodesItem => {
									let desc = [];
									nodesItem.desc.forEach(descItem => {
										desc.push(descItem.name);
									});
									that.$service.goods.specification
										.add({
											parentId: res.id,
											name: nodesItem.name,
											desc: desc.join(',')
										})
										.then(() => {
											close();
											that.$service.goods.specification.list().then(res => {
												that.skuList = res;
											});
										})
										.catch(err => {
											that.$message.error(err.message);
											done();
										});
								});
							})
							.catch(err => {
								that.$message.error(err.message);
								done();
							});
					}
				}
			});
		},
		onChange() {
			this.$emit(
				'input',
				JSON.stringify({
					skuInfo: [
						{
							name: '规格',
							desc: this.form[0].specification
						}
					],
					specifications: this.form
				})
			);
		},
		onSkuSelect(val) {
			this.skuList.forEach(item => {
				if (val === item.id) {
					item.nodes.forEach(node => {
						let desc = [];
						node.desc.split(',').forEach(descItem => {
							desc.push({
								name: descItem
							});
						});
						node.descResult = desc;
					});
					this.nodes = item.nodes;
				}
			});
			this.onValueEmit();
		},
		onSkuCreate() {
			if (this.nodes.length === 0) {
				this.$message.error('请选择规格模板');
				return false;
			}
			// 校验规格是否有空值
			let flag = true;
			this.nodes.forEach(item => {
				if (!item.name) {
					flag = false;
					this.$message.error('规格名不能为空');
					return false;
				}
				item.descResult.forEach(desc => {
					if (!desc.name) {
						flag = false;
						this.$message.error('规格值不能为空');
						return false;
					}
				});
			});
			if (flag) {
				let nodesArr = [];
				this.resultNodes = [];

				this.nodes.forEach(item => {
					let descResultArr = [];
					item.descResult.forEach(descResultItem => {
						descResultArr.push(descResultItem.name);
					});
					nodesArr.push(descResultArr);
				});

				let resultNodesArr = this.onSkuCombination(nodesArr);
				resultNodesArr.forEach(item => {
					this.resultNodes.push({
						specification: item,
						endprice: '',
						costprice: '',
						price: '',
						surplus: ''
					});
				});
				this.onValueEmit();
			}
		},
		// 交叉生成算法
		onSkuCombination(arr) {
			var heads = arr[0];
			for (var i = 1, len = arr.length; i < len; i++) {
				if (arr[i].length) {
					heads = this.addNewType(heads, arr[i]);
				}
			}
			return heads;
		},
		addNewType(heads, choices) {
			var result = [];
			for (var i = 0, len = heads.length; i < len; i++) {
				for (var j = 0, lenj = choices.length; j < lenj; j++) {
					result.push(heads[i] + ',' + choices[j]);
				}
			}
			return result;
		},
		onSkuDelete(index) {
			this.nodes = this.nodes.filter((item, itemIndex) => {
				if (itemIndex === index) {
					return false;
				} else {
					return true;
				}
			});
			this.onValueEmit();
		},
		onSkuAdd() {
			this.nodes.push({
				name: '',
				desc: '',
				descResult: [
					{
						name: ''
					}
				]
			});
			this.$forceUpdate();
			this.onValueEmit();
		},
		onValueDelete(index, skuIndex) {
			this.nodes[index].descResult = this.nodes[index].descResult.filter(
				(item, itemIndex) => {
					if (itemIndex === skuIndex) {
						return false;
					} else {
						return true;
					}
				}
			);
			this.$forceUpdate();
			this.onValueEmit();
		},
		onValueAdd(index) {
			this.nodes[index].descResult.push({
				name: ''
			});
			this.$forceUpdate();
			this.onValueEmit();
		},
		onValueInput() {
			this.$forceUpdate();
			this.onValueEmit();
		},
		onValueEmit() {
			let skuInfo = [];
			this.nodes.forEach(nodesItem => {
				let desc = [];
				nodesItem.descResult.forEach(descResultItem => {
					desc.push(descResultItem.name);
				});
				skuInfo.push({
					name: nodesItem.name,
					desc: desc.join(',')
				});
			});
			this.$emit(
				'input',
				JSON.stringify({
					skuInfo: skuInfo,
					specifications: this.resultNodes
				})
			);
		},
		onBitchEndprice(val) {
			this.resultNodes.forEach(item => {
				item.endprice = val;
			});
			this.onValueEmit();
		},
		onBitchCostprice(val) {
			this.resultNodes.forEach(item => {
				item.costprice = val;
			});
			this.onValueEmit();
		},
		onBitchPrice(val) {
			this.resultNodes.forEach(item => {
				item.price = val;
			});
			this.onValueEmit();
		},
		onBitchSurplus(val) {
			this.resultNodes.forEach(item => {
				item.surplus = val;
			});
			this.onValueEmit();
		}
	},
	watch: {
		value(val) {
			if (!val) {
				return;
			}
			if (!this.isFirst) {
				this.isFirst = true;
				let value = JSON.parse(this.value);
				if (value.operate === 'edit') {
					let specification = value.specifications;
					if (specification.length > 1) {
						this.radio = '2';

						specification.forEach(item => {
							this.resultNodes.push({
								specification: item.specification,
								endprice: item.endprice,
								costprice: item.costprice,
								price: item.price,
								surplus: item.surplus,
								id: item.id
							});
						});
					} else {
						this.radio = '1';
						this.form = specification;
					}

					this.nodes = [];
					let skuInfo = JSON.parse(value.skuInfo);
					skuInfo.forEach(item => {
						let desc = [];
						item.desc.split(',').forEach(descItem => {
							desc.push({
								name: descItem
							});
						});
						this.nodes.push({
							name: item.name,
							descResult: desc
						});
					});

					this.onValueEmit();
				}
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.sku-select {
	.sku-type {
		/*flexBox(flex-start);*/
	}
	.sku-table {
		border: 1px solid #e6e6e6;
		td {
			border: 1px solid #e6e6e6;
		}
	}
	/deep/.el-radio {
		margin-bottom: 10px;
	}
	/deep/ .el-form {
		white-space: nowrap;
		.el-form-item {
			margin: 0;
			.el-form-item__label {
				display: block;
				width: 100% !important;
				text-align: center;
				background: #f2f2f2;
				border: 1px solid #e6e6e6;
				padding: 0 10px;
				border-right: none;
			}
			.el-form-item__content {
				padding: 10px;
				border: 1px solid #e6e6e6;
				border-top: none;
				border-right: none;
				.el-input {
					width: 110px;
				}
			}
			&:last-child {
				.el-form-item__label,
				.el-form-item__content {
					border-right: 1px solid #e6e6e6;
				}
			}
		}
	}
	.sku-single {
	}
	.sku-multi {
		max-height: 600px;
		overflow: auto;
		margin-bottom: 20px;
		.sku-nodes {
			margin-bottom: 10px;
		}
	}
	.specification {
		width: 170px;
		text-align: center;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
}
</style>
